package a66weding.com.jiehuntong.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;

import org.xutils.common.util.DensityUtil;

import java.util.ArrayList;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.common.CommonHandler;
import a66weding.com.jiehuntong.common.CommonPagerAdapter;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.CacheUtils;
import a66weding.com.jiehuntong.view.DirectionViewPager;
import a66weding.com.jiehuntong.wx.Util;

public class GuideActivity extends Activity  implements View.OnClickListener{
    private DirectionViewPager  mViewPager;
    private LinearLayout mTopLooperLay;
    private ImageView mRedpoint;
    private List<ImageView> imgList;
    private boolean mExitFlag;
    private MyHandler mHandler;
    private boolean isToLogin;
    private static final int WHAT_EXIT_FLAG = 0x128;
    private static final int WHAT_TONEXT = 0x130;
    private int distance=DensityUtil.dip2px( 10)*2;
    private int px = DensityUtil.dip2px(10);
    private int index;
    private int mCurrentPosition;
    private boolean showGuide = true;
    private List<ImageView> mPointList;
    private TextView enterIntoButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guide);
        ((GlobalApplication)getApplication()).getActivityManager().addActivity("GuideActivity",this);
        index = getIntent().getIntExtra("index", 0);
        int versionCode = CacheUtils.getIntFromCache(this, "versionCode");
        int versionCodeCurrent = CUtils.getVersionCode(this);
        if(versionCodeCurrent <= versionCode) {
            showGuide = false;
            startActivity();
            return;
        }
        initView();
        initData();
    }
    private void initView() {
        mViewPager = (DirectionViewPager ) findViewById(R.id.viewpager_guide);
        mTopLooperLay = (LinearLayout) findViewById(R.id.llay_homeitem_toppoint);
        mRedpoint = (ImageView)findViewById(R.id.iv_guide_redpoint);
        mViewPager.addOnPageChangeListener(monPageChangeListener);
        mViewPager.setCurrentItem(index);
        enterIntoButton = (TextView) findViewById(R.id.enter_into_button);
        enterIntoButton.setOnClickListener(this);
        enterIntoButton.setVisibility(View.GONE);
    }

    private void initData() {
        mHandler=new MyHandler(this);
        int [] guidids={R.mipmap.guide_1,R.mipmap.guide_2,R.mipmap.guide_3,R.mipmap.guide_4};

        imgList=new ArrayList<ImageView>();
        Bitmap bitmap=null;
        ImageView imageView=null;
        ImageView mPointView=null;
        for (int i = 0; i < guidids.length; i++) {
            imageView = new ImageView(this);
            imageView.setBackgroundResource(guidids[i]);
            imgList.add(imageView);

            mPointView=new ImageView(this);
            mPointView.setBackgroundResource(R.drawable.guide_scaleview_shape);

        }

        if(imgList!=null && imgList.size()>0) {
            mViewPager.setAdapter(new CommonPagerAdapter<ImageView>(imgList) {
                @Override
                protected View getView(int position) {
                    ImageView imageView1 = imgList.get(position);
                    imageView1.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    return imageView1;
                }
            });


            mPointList=new ArrayList<ImageView>();

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);
            ImageView imageView2=null;
            mPointList.clear();
            for (int i = 0; i < guidids.length; i++) {
                imageView2=new ImageView(this);
                imageView2.setBackgroundResource(R.drawable.splash_graypoint_shape);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DensityUtil.dip2px(10),
                        DensityUtil.dip2px(10));
                if(i!=0) {
                    params.leftMargin=DensityUtil.dip2px(10);
                }
                mPointList.add(imageView2);
                mTopLooperLay.addView(imageView2,params);
            }
        }


    }

        /**
         * ViewPager页面变化的监听
         */
    ViewPager.OnPageChangeListener monPageChangeListener=new ViewPager.OnPageChangeListener() {
        /**
         *
         * @param position 滑动页面的位置
         * @param positionOffset 滑动页面的百分比
         * @param positionOffsetPixels 滑动的像素
         */
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {


            float redpointdx = distance * (position+positionOffset);
            int disten = (imgList.size() - 1) * distance;
            RelativeLayout.LayoutParams params =
                    new RelativeLayout.LayoutParams(px, px);
            params.leftMargin= (int) redpointdx;
            if(redpointdx>disten) {
                params.leftMargin= 0;
            }
            mRedpoint.setLayoutParams(params);

        }

        /**
         * 当前屏幕显示的图片位置
         * @param position
         */
        @Override
        public void onPageSelected(int position) {
            mCurrentPosition=position;

            if(position==imgList.size()-1) {
                enterIntoButton.setVisibility(View.VISIBLE);
            } else {
                enterIntoButton.setVisibility(View.GONE);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            if(mCurrentPosition==imgList.size()-1  ) {

            }
        }
    };
    ViewTreeObserver.OnGlobalLayoutListener monGloballLayoutListener=
            new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {

                }
            };
    private void startActivity(){
        Intent intent = new Intent(this, SMSFastLoginActivity.class);
        intent.putExtra("isCanBack",false);
        startActivity(intent);
        finish();
    }
    /**
     * 再按一次退出
     */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        /*if (KeyEvent.KEYCODE_BACK == keyCode) {
           if (!mExitFlag) {
                CUtils.showToast(R.string.dblclick_to_exit);
                mExitFlag = true;
                mHandler.sendEmptyMessageDelayed(WHAT_EXIT_FLAG, 2000);
                return true;
            }else if(mExitFlag){
               ((GlobalApplication)getApplication()).getActivityManager().exitApp();
           }
        }*/
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        CacheUtils.setIntToCache(GuideActivity.this, "versionCode", CUtils.getVersionCode(GuideActivity.this));
        mHandler.sendEmptyMessage(WHAT_TONEXT);
    }


    /**
     * 自定义 Handler, 用于实现按两次退出
     */
    class MyHandler extends CommonHandler<GuideActivity> {
        public MyHandler(GuideActivity activity) {
            super(activity);
        }

        @Override
        protected void handle(GuideActivity activity, Message msg) {
            switch (msg.what) {
                case WHAT_EXIT_FLAG:
                    if (null != activity) {
                        activity.mExitFlag = false;

                    }
                    break;
                case WHAT_TONEXT:
                    if (null != activity) {
                        startActivity();
                    }
                    break;
            }
        }
    }
    @Override
    protected void onStop() {
        if(!showGuide){
            super.onStop();
            return;
        }
        super.onStop();
    }
    @Override
    protected void onDestroy() {
        if(!showGuide){
            super.onDestroy();
            return;
        }
        if (imgList != null) {
            for (int i = 0; i < imgList.size(); i++) {
                ImageView imageView = imgList.get(i);
                if (imageView != null) {
                    Util.releaseImageView(imageView);
                }
            }
            imgList = null;
        }
        if (mPointList != null) {
            for (ImageView m : mPointList) {
                Util.releaseImageView(m);
            }
            mPointList = null;
        }
        mHandler.removeCallbacksAndMessages(null);
        mHandler = null;
        mViewPager = null;
        mTopLooperLay = null;
        mRedpoint = null;
        imgList = null;
        mPointList = null;
        enterIntoButton = null;
        super.onDestroy();
    }

    private void releaseImageView(ImageView imageView) {
        Drawable d = imageView.getDrawable();
        if (d != null)
            d.setCallback(null);
        imageView.setImageDrawable(null);
        imageView.setBackgroundDrawable(null);
    }


    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

}
